package it.fantacalcio.spring.service;

import it.fantacalcio.hibernate.dao.PartitaDAO;
import it.fantacalcio.hibernate.sessionfactory.HibernateSessionFactory;
import it.fantacalcio.model.Partita;

import java.util.List;

import org.hibernate.Transaction;

public class PartitaServiceImpl implements PartitaService {
	private PartitaDAO partitaDAO;
	
	public PartitaDAO getPartitaDAO() {
		return partitaDAO;
	}

	public void setPartitaDAO(PartitaDAO partitaDAO) {
		this.partitaDAO = partitaDAO;
	}
	
	//----------------------------------------------------------------------------------
	
	@Override
	public int salva(Partita partita) throws Exception {
		if(partita==null){
			return -1;
		}
		try{
			Transaction tx = HibernateSessionFactory.getSession().beginTransaction();
			partitaDAO.save(partita);
			tx.commit();
		}catch(Exception e){
			e.printStackTrace();
			return -2;
		}
		return 1;
	}
	
	@Override
	public int cancella(Partita partita) throws Exception {
		if(partita==null || partita.getId()<1){
			return -1;
		}
		try{
			Transaction tx = HibernateSessionFactory.getSession().beginTransaction();
			partitaDAO.delete(partita);
			tx.commit();
		}catch(Exception e){
			e.printStackTrace();
			return -2;
		}
		return 1;
	}
	
	@Override
	public int modifica(Partita partita) throws Exception {
		if(partita==null || partita.getId()<1){
			return -1;
		}
		try{
			Transaction tx = HibernateSessionFactory.getSession().beginTransaction();
			partitaDAO.update(partita);
			tx.commit();
		}catch(Exception e){
			e.printStackTrace();
			return -2;
		}
		return 1;
	}
	
	@Override
	public Partita get(Long id) throws Exception {
		if(id<1){
			return null;
		}
		Transaction tx = HibernateSessionFactory.getSession().beginTransaction();
		Partita partita = partitaDAO.get(id);
		tx.commit();
		return partita;
	}

	@Override
	public List<Partita> list() throws Exception {
		Transaction tx = HibernateSessionFactory.getSession().beginTransaction();
		List<Partita> result=partitaDAO.list();
		tx.commit();
		return result;
	}

	@Override
	public List<Partita> findByExample(Partita partita) throws Exception {
		if(partita==null){
			return null;
		}
		Transaction tx = HibernateSessionFactory.getSession().beginTransaction();
		List<Partita> result=partitaDAO.findByExample(partita);
		tx.commit();
		return result;
	}

}
